package com.fresh.fresh.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.fresh.fresh.dao.User;
import com.fresh.fresh.service.UserService;
import com.fresh.fresh.utils.Result;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/user")
@Api(tags = "用户接口")
public class UserController {

    @Autowired
    UserService userService;

    @PostMapping("/login")
    @ApiOperation("用户登录接口")
    public Result<?> login(@RequestBody User user) {
        User data = userService.login(user);
        if (data != null) {
            return Result.success(data);
        } else {
            return Result.fail("用户密码错误或账号不存在！");
        }
    }

    @PostMapping("/register")
    @ApiOperation("用户注册接口")
    public Result<?> register(@RequestBody User user) {
        LambdaQueryWrapper<User> data = new LambdaQueryWrapper<>();
        data.eq(User::getUsername, user.getUsername());
        List<User> res = userService.list(data);
        if (!res.isEmpty()) {
            return Result.fail("已有账号！请重新输入");
        } else {
            userService.register(user);
            return Result.success("注册成功");
        }

    }

    @GetMapping("/message/id={id}")
    @ApiOperation("获取用户信息接口")
    public Result<?> getMessage(@PathVariable Integer id) {
        User data = userService.getById(id);
        return Result.success(data);
    }

    //用户信息修改
    @PostMapping("/update")
    @ApiOperation("修改用户信息接口")
    public Result<?> update(@RequestBody User user){
        userService.updateById(user);
        return Result.success("成功");
    }


}
